package com.tool.emulator.common;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Util.java @author tl 2011-6-18
 */
public class Util {
	public static void dumpBytes(int addr, byte[] b) {
		PrintWriter out = new PrintWriter(System.out, true);
		dumpBytes(out, addr, b);
	}

	public static void dumpBytes(PrintWriter out, int addr, byte[] b) {
		for (int i = 0; i < b.length; i++, addr++) {
			if (addr % 16 == 0 || i == 0) {
				out.println();
				out.print(w2s(addr) + ": ");
			}
			out.print(" " + b2s(b[i]));
		}
		out.println();
	}

	public static String b2s(int b) {
		String s = "00" + Integer.toHexString(b).toUpperCase();
		return s.substring(s.length() - 2);
	}

	public static String w2s(int w) {
		String s = "0000" + Integer.toHexString(w).toUpperCase();
		return s.substring(s.length() - 4);
	}

	public static String slKey(Field f) {
		int m = f.getModifiers();
		if (!Modifier.isStatic(m)
				&& !Modifier.isTransient(m)
				&& !Modifier.isStatic(m)
				&& !Modifier.isFinal(m)) {
			return f.getDeclaringClass().getName() + "/" + f.getName() + "/" + f.getType().getName();
		}
		return null;
	}

	public static DataInputStream openFile(File file, String tag) throws Exception {
		boolean ok = false;
		DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
		try {
			for (int i = 0; i < tag.length(); i++) {
				if (in.read() != tag.charAt(i))
					throw new IOException(file.getAbsolutePath() + " is not a " + tag + " file");
			}
			ok = true;
			return in;
		} finally {
			if (!ok)
				in.close();
		}
	}

	public static DataOutputStream saveFile(File file, String tag) throws Exception {
		boolean ok = false;
		DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
		try {
			for (int i = 0; i < tag.length(); i++)
				out.write(tag.charAt(i));
			ok = true;
			return out;
		} finally {
			if (!ok)
				out.close();
		}
	}
}
